package cn.hughie.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author yuh
 * @Date Created in 下午8:38 2018/5/25
 * @Description
 */
public class Main {

    public static void insert(User user) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();
        Class<? extends User> aClass = user.getClass();
        boolean annotationPresent = aClass.isAnnotationPresent(Table.class);
        if (annotationPresent) {
            Table annotationsByType = aClass.getAnnotation(Table.class);
            String tableName = annotationsByType.value();
            s1.append("insert into ").append(tableName).append(" (");
            s2.append("(");
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (declaredField.isAnnotationPresent(Column.class)) {
                    Column column = declaredField.getAnnotation(Column.class);
                    String columnName = column.value();
                    s1.append(columnName).append(",");
                    Method method = aClass.getMethod("get" + declaredField.getName().substring(0, 1).toUpperCase() + declaredField.getName().substring(1));
                    Object val = method.invoke(user);
                    s2.append(val).append(",");
                }
            }
            s1.delete(s1.length()-1,s1.length());
            s2.delete(s2.length()-1,s2.length());
            String s = s1.append(")").toString() + " values " + s2.toString() + ");";
            System.out.println(s);
        }
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        User user = new User();
        user.setId(1L);
        user.setName("是哦");
        insert(user);
    }
}
